import planIcon from '@/assets/img/plan_icon.png';
import planIconDark from '@/assets/img/plan_icon_dark.png';
import planIconGre from '@/assets/img/plan_icon_gre.png';
import { Button, Checkbox, Modal, Select } from 'antd';
import React, { useEffect, useState } from 'react';
import styles from './index.less';
// @ts-ignore
import emitter from '#/utils/events';

interface StatusOption {
  label: string;
  value: number | string;
}

interface Props {
  statusOption: StatusOption[];
  issueStatusChange?: any;
  timeOptions?: StatusOption[];
  noTimeOptions?: StatusOption[];
  reTime?: any;
}

interface Option {
  label: string;
  value: number | string;
  disabled?: boolean;
}

interface SelectValue {
  labels: string[];
  values: (number | string)[];
}

const TjSequenceSelect: React.FC<Props> = ({
  statusOption = [],
  issueStatusChange,
  timeOptions,
  noTimeOptions,
  reTime,
}) => {
  const [visible, setVisible] = useState(false);
  const [theme, setTheme] = useState(localStorage.getItem('saas-theme') || 'dark');
  const [selectedCategory, setSelectedCategory] = useState<SelectValue>(() => {
    if (statusOption && statusOption.length > 0) {
      return {
        labels: [...statusOption.map((item) => item.label)],
        values: [...statusOption.map((item) => item.value)],
      };
    }
    return {
      labels: [],
      values: [],
    };
  });
  const [noSequenceCheckedList, setNoSequenceCheckedList] = useState<string[]>(
    () => statusOption?.map((item) => item.value as string) || [],
  );

  const [sequenceCheckedList, setSequenceCheckedList] = useState<string[]>(
    () => statusOption?.map((item) => item.value as string) || [],
  );
  const options: Option[] = noTimeOptions || [];
  const options2: Option[] = timeOptions || [];
  const [lastConfirmedState, setLastConfirmedState] = useState({
    noSequenceChecked: noSequenceCheckedList,
    sequenceChecked: sequenceCheckedList,
    selected: selectedCategory,
  });

  // 复选框不可跨序列选择
  /* const handleCheckboxChangeNo = (checkedValues: any[]) => {
    const selectedItems = options.filter(item => checkedValues.includes(item.value));
    setNoSequenceCheckedList(checkedValues);
    setSequenceCheckedList([]);
    setSelectedCategory({
      labels: selectedItems.map(item => item.label),
      values: checkedValues
    });
  };

  const handleCheckboxChange = (checkedValues: any[]) => {
    const selectedItems = options2.filter(item => checkedValues.includes(item.value));
    setSequenceCheckedList(checkedValues);
    setNoSequenceCheckedList([]);
    setSelectedCategory({
      labels: selectedItems.map(item => item.label),
      values: checkedValues
    });
  }; */

  const handleCheckboxChangeNo = (checkedValues: any[]) => {
    const selectedItems = options.filter((item) => checkedValues.includes(item.value));
    setNoSequenceCheckedList(checkedValues);
    setSelectedCategory({
      labels: [
        ...selectedItems.map((item) => item.label),
        ...options2
          .filter((item) => sequenceCheckedList.includes(String(item.value)))
          .map((item) => item.label),
      ],
      values: [...checkedValues, ...sequenceCheckedList],
    });
  };

  const handleCheckboxChange = (checkedValues: any[]) => {
    const selectedItems = options2.filter((item) => checkedValues.includes(item.value));
    setSequenceCheckedList(checkedValues);
    setSelectedCategory({
      labels: [
        ...selectedItems.map((item) => item.label),
        ...options
          .filter((item) => noSequenceCheckedList.includes(String(item.value)))
          .map((item) => item.label),
      ],
      values: [...checkedValues, ...noSequenceCheckedList],
    });
  };

  const handlerSure = () => {
    setVisible(false);
    const noTimeOptionsValues = noTimeOptions?.map((item) => item.value as string) || [];
    const timeOptionsValues = timeOptions?.map((item) => item.value as string) || [];
    const allContractTypes = [...noTimeOptionsValues, ...timeOptionsValues];
    issueStatusChange(selectedCategory.values, allContractTypes);

    setLastConfirmedState({
      noSequenceChecked: noSequenceCheckedList,
      sequenceChecked: sequenceCheckedList,
      selected: selectedCategory,
    });
  };

  const handlerCancel = () => {
    setNoSequenceCheckedList(lastConfirmedState.noSequenceChecked);
    setSequenceCheckedList(lastConfirmedState.sequenceChecked);
    setSelectedCategory(lastConfirmedState.selected);
    setVisible(false);
  };

  // 格式化显示下拉文本
  const formatSelectedText = (labels: string[]) => {
    if (labels.length === 0 || labels.every((label) => label === '')) {
      return [];
    }

    if (labels.length === 1) {
      return [labels[0]];
    }

    return [labels[0], `+${labels.length - 1}...`];
  };

  const handleDeselect = (value: string) => {
    // 如果是+N形式的值，清除除第一个之外的所有选中项
    if (value.startsWith('+')) {
      const firstLabel = selectedCategory.labels[0];
      const firstValue = selectedCategory.values.find(
        (_, index) => selectedCategory.labels[index] === firstLabel,
      );

      setSelectedCategory({
        labels: [firstLabel],
        values: [firstValue ?? selectedCategory.values[0]],
      });

      setNoSequenceCheckedList((prevList) =>
        prevList.filter(
          (item) => options.find((opt) => String(opt.value) === item)?.label === firstLabel,
        ),
      );
      setSequenceCheckedList((prevList) =>
        prevList.filter(
          (item) => options2.find((opt) => String(opt.value) === item)?.label === firstLabel,
        ),
      );

      setTimeout(() => {
        const noTimeOptionsValues = noTimeOptions?.map((item) => item.value as string) || [];
        const timeOptionsValues = timeOptions?.map((item) => item.value as string) || [];
        const allContractTypes = [...noTimeOptionsValues, ...timeOptionsValues];

        issueStatusChange([firstValue ?? selectedCategory.values[0]], allContractTypes);

        setLastConfirmedState({
          noSequenceChecked: noSequenceCheckedList.filter(
            (item) => options.find((opt) => String(opt.value) === item)?.label === firstLabel,
          ),
          sequenceChecked: sequenceCheckedList.filter(
            (item) => options2.find((opt) => String(opt.value) === item)?.label === firstLabel,
          ),
          selected: {
            labels: [firstLabel],
            values: [firstValue ?? selectedCategory.values[0]],
          },
        });
      }, 0);
    } else {
      const newLabels = selectedCategory.labels.filter((label) => label !== value);
      const newValues = selectedCategory.values.filter(
        (_, index) => selectedCategory.labels[index] !== value,
      );

      setSelectedCategory({
        labels: newLabels,
        values: newValues,
      });

      const valueToRemove = selectedCategory.values.find(
        (_, index) => selectedCategory.labels[index] === value,
      );

      setNoSequenceCheckedList((prevList) =>
        prevList.filter((item) => item !== String(valueToRemove)),
      );
      setSequenceCheckedList((prevList) =>
        prevList.filter((item) => item !== String(valueToRemove)),
      );

      setTimeout(() => {
        const noTimeOptionsValues = noTimeOptions?.map((item) => item.value as string) || [];
        const timeOptionsValues = timeOptions?.map((item) => item.value as string) || [];
        const allContractTypes = [...noTimeOptionsValues, ...timeOptionsValues];

        issueStatusChange(newValues, allContractTypes);

        setLastConfirmedState({
          noSequenceChecked: noSequenceCheckedList.filter((item) => item !== String(valueToRemove)),
          sequenceChecked: sequenceCheckedList.filter((item) => item !== String(valueToRemove)),
          selected: {
            labels: newLabels,
            values: newValues,
          },
        });
      }, 0);
    }
  };

  useEffect(() => {
    if (reTime) {
      setSequenceCheckedList([]);
      setNoSequenceCheckedList([]);
      setSelectedCategory({ labels: [], values: [] });
    }
  }, [reTime]);

  useEffect(() => {
    emitter.addListener('onGlobalThemeChange', (e: { key: React.SetStateAction<string> }) => {
      setTheme(e.key);
    });
    return () => {
      emitter.removeListener('onGlobalThemeChange', () => {});
    };
  }, []);

  return (
    <>
      <Select
        placeholder={'序列选择'}
        mode="multiple"
        value={formatSelectedText(selectedCategory.labels)}
        open={false}
        onClick={() => setVisible(true)}
        style={{ width: 200 }}
        onDeselect={handleDeselect}
        className={styles.sequenceSelect}
      />

      <Modal
        className={styles.modal}
        visible={visible}
        width={578}
        centered
        onCancel={handlerCancel}
        title={
          <div className={styles.titleDiv}>
            <img
              src={theme === 'dark' ? planIconDark : theme === 'gre' ? planIconGre : planIcon}
              width="30px"
              height="30px"
            />
            <span>{'序列选择'}</span>
            {/* <Tooltip
              overlayStyle={{
                fontSize: 12,
              }}
              arrowPointAtCenter
              title={"多选状态下不能跨时序选择"}
            >
              <QuestionCircleOutlined className={styles.icon} />
            </Tooltip> */}
          </div>
        }
        style={{ borderRadius: 6 }}
        footer={[
          <Button onClick={handlerCancel}>取消</Button>,
          <Button type="primary" onClick={handlerSure}>
            确定
          </Button>,
        ]}
      >
        <div className={styles.content}>
          <div className={styles.checkBox}>
            {noTimeOptions && noTimeOptions.length > 0 ? (
              <>
                <div style={{ marginBottom: 4 }}>无时序序列</div>
                <Checkbox.Group
                  options={options}
                  value={noSequenceCheckedList}
                  onChange={handleCheckboxChangeNo}
                  className={styles.noIemGroup}
                />
              </>
            ) : (
              <div>无时序序列: 暂无数据</div>
            )}
            {timeOptions && timeOptions.length > 0 ? (
              <>
                <div style={{ margin: '4px 0 4px 0' }}>时序序列</div>
                <Checkbox.Group
                  options={options2}
                  value={sequenceCheckedList}
                  onChange={handleCheckboxChange}
                  className={styles.itemGroup}
                />
              </>
            ) : (
              <div style={{ marginTop: 12 }}>时序序列: 暂无数据</div>
            )}
          </div>
        </div>
      </Modal>
    </>
  );
};

export default TjSequenceSelect;
